package com.st.controller;

import com.st.lock.util.RedisLock;
import com.st.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;


@Controller
public class TestController {

    @Autowired
    private RedisLock redisLock;

    @Autowired
    private TestService testService;

    /**
     * 秒杀的场景下
     *
     * @return
     */
    @RequestMapping("/test")
    @ResponseBody
    public Map test() {
        Map result = new HashMap();
        int time = 10;
        // 这个requestId是为了释放锁（不能释放别人的锁）和给锁续命（给自己的锁续命）的时候用的，用来区分本次操作的唯一标识
        String requestId = UUID.randomUUID().toString().replace("-", "") + (new Random().nextInt(9000) + 1000);
        //尝试获取锁
        redisLock.tryGetLock(requestId, time);
        //启动子线程给锁续命
        Thread t1 = redisLock.createLifeThread(time, requestId);
        try {
            //守护线程
            t1.setDaemon(true);
            //启动续命线程
            t1.start();
            result.put("num", testService.updateNum());
            result.put("tid:", requestId);
        } finally {
            //停止续命线程
            t1.interrupt();
            //释放锁
            redisLock.releaseLock(requestId);
        }
        return result;
    }


    @RequestMapping("/test1")
    @ResponseBody
    public Map test1() {
        Map result = new HashMap();
        result.put("num", testService.updateNum());
        return result;
    }

}
